package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.TravelUserIdFavors;
import cn.wolfcode.wolf2w.redis.service.ITravelUserIdFavorsRedisService;
import cn.wolfcode.wolf2w.service.ITravelUserIdFavorsService;
import cn.wolfcode.wolf2w.util.RidesKey;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class TravelUserIdFavorsRedisServiceImpl implements ITravelUserIdFavorsRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ITravelUserIdFavorsService travelUserIdFavorsService;

    @Override
    public boolean isTravelUserIdFavorsExist(String usid) {
        String key = RidesKey.TRAVEL_USER_ID.join(usid);
        if (redisTemplate.hasKey(key)){
            return true;
        }
        return false;
    }

    @Override
    public void setTravelUserIdFavorsRedis(TravelUserIdFavors travelUserIdFavors) {
        String key = RidesKey.TRAVEL_USER_ID.join(travelUserIdFavors.getUsid());
        redisTemplate.opsForValue().set(key, JSON.toJSONString(travelUserIdFavors));
    }

    @Override
    public List<TravelUserIdFavors> findAllTravelUserIdFavors() {
        String patten = RidesKey.TRAVEL_USER_ID.join("*");
        Set<String> keys = redisTemplate.keys(patten);
        ArrayList<TravelUserIdFavors> travelUserIdFavors = new ArrayList<>();
        for (String key : keys) {
            String favors = redisTemplate.opsForValue().get(key);
            travelUserIdFavors.add(JSON.parseObject(favors,TravelUserIdFavors.class));
        }
        return travelUserIdFavors;
    }

    @Override
    public void setMongodb(List<TravelUserIdFavors> travelUserIdFavors) {
        for (TravelUserIdFavors travelUserIdFavor : travelUserIdFavors) {
            travelUserIdFavorsService.update(travelUserIdFavor);
        }
    }
}

